// subPages/business/statistics/statistics.js
import * as echarts from '../../../ec-canvas/echarts';
const app = getApp()
var healthUtil =  require('../../../utils/healthUtil.js');
var util =  require('../../../utils/util.js');
let LineChart = null
let LineChart2 = null
let BarChart = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navList: [{nav: '周'},{nav: '月'}],
    currentTab: 0,
    currentTab2: 0,    
    ec: {
      // lazyLoad: true // 延迟加载
    },
    ec2: {
      // lazyLoad: true // 延迟加载
    },
    ec3: {
      // lazyLoad: true // 延迟加载
    },
    num2: 7,
    num3: 7,
    isShop: false,
    isItemCommunity: false,
    isData2: false,
    downImg: '/resources/business/down2.png',
    upImg: '/resources/business/up2.png',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      shopType: app.globalData.shopType,
      curTime: (new Date(util.setTime(new Date()).replace(/-/g,"/") + ' 00:00:00').getTime())
    })
    that.getData()
    switch (that.data.shopType) {
      case '0':
      case '1':
        that.getShopAllData()
        that.setData({
          isShop: true
        })
        break;
      case '3':
        if(app.globalData.mainType == 1){
          that.getCommunity()
        }
        break;
    }
    
  },

  //获取下级区代
  getCommunity:function(){
    var that = this
    util.getAjax(`${app.globalData.apiUrl}/Api/Admincommunity/get_son_community`,function(res){
      console.log(res)
      if(res.data.length!=0){
        var communityArray = []
        for(var i in res.data){
          communityArray.push(res.data[i])
        }
        that.setData({
          isItemCommunity: true,
          communityImgSrc: that.data.downImg,
          communityArray: communityArray,
        })
      }
    },{community_id: app.globalData.shopId})
  },

  //获得数据
  getData:function(){
    var that = this
    var start_time = (that.data.curTime - (that.data.num2 * 3600 * 24 * 1000)) / 1000;
    var end_time = (new Date(util.setTime(new Date()).replace(/-/g,"/") + ' 23:59:59').getTime())/1000;
    var urlType = ''
    var data = {}
    switch (app.globalData.shopType) {
      case '0':
        urlType = 'get_service_shop_sy_picture';
        data = {shop_id: app.globalData.shopId,start_time: start_time,end_time: end_time}
        break;
      case '1':
        urlType = 'get_health_shop_sy_picture';
        data = {shop_id: app.globalData.shopId,start_time: start_time,end_time: end_time}
        break;
      case '2':
        urlType = 'get_service_kitchen_sy_picture';
        data = {kitchen_id: app.globalData.shopId,start_time: start_time,end_time: end_time}
        break;
      case '3':
        urlType = 'admin_community_get_community_sy_picture';
        data = {community_id: app.globalData.shopId,start_time: start_time,end_time: end_time}
        break;
    }
    util.getAjax(`${app.globalData.apiUrl}/${urlType}`,function(res){
      console.log(res)
      if(res.data.length != 0){
        var list = that.setNewList(res.data)
        list = list.reverse()
        var dateList = []
        var dataList = []
        for(var i in list){
          dateList.push(list[i].date);
          dataList.push(list[i].total_price.toFixed(2))
        }
        that.setData({
          isData: true,        
          dataList: dataList,
          dateList: dateList,
        })
        that.linechartsComponnet = that.selectComponent('#mychartLine');
        LineChart = null
        that.getLineGraphData();  //创建图表
      }else{
        that.setData({
          isData: false
        })
      }
    },data)
  },

  setNewList:function(res){
    let arr = [];
    for(let i=0;i<res.length;i++){
        let date = res[i].date;
        let total = Number(res[i].price);
        for(let j=i+1;j<res.length;j++){
            // console.log(res);
            if(res[i].date == res[j].date){
                total+= Number(res[j].price);
                res.splice(j,1)
                j--;
            }
        }
        let profit_item = {
            date:date,
            total_price:total
        };
        arr.push(profit_item)
    }
    return arr;
  },

  //线图表
  getLineGraphData:function(){
    var that = this
    if (!LineChart){
      that.init_LineEcharts(); //初始化图表
    }else{
      that.setLineOption(); //更新数据
    }
  },

  //初始化图表
  init_LineEcharts: function () {
    var that = this
    that.linechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      LineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      LineChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setLineOption();
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return LineChart;
    });
  },

  setLineOption: function () {
    LineChart.clear();  // 清除
    LineChart.setOption(this.getLineOption());  //获取新数据
  },

  //设置折线图表
  getLineOption: function () {
    var that = this
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: '',
        subtext: ''
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:30,
        x2:0,
        y2:0,
        containLabel: true
      },
      xAxis: { 
        type: 'category',
        show:true,
        boundaryGap:true,
        data : that.data.dateList,
        axisLine:{
          show:true,
          lineStyle:{
            color: '#e0e7ff',
            width: 1,
          }
        },
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          color: '#666666',
          interval: 0,
          formatter: '{value}',
          formatter:function(value){
            // console.log(value)
            return util.setTime3(value)
          }
        },
      },
      yAxis: {
        type: 'value',
        boundaryGap:false,
        show:true,
        scale: false,
        splitNumber:2,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine:{
          show:true,
          lineStyle:{
            color: '#e0e7ff',
          }
        },
        axisLabel:{
          show: true,
          inside: true,
          verticalAlign: 'bottom',
          margin: 0,
          color: '#666666',
          formatter:function(value,index){
            // console.log(value)
            return value + '元'
          }
        },
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: healthUtil.dataZoom(that.data.dateList),
          end: 100,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'',
        type:'line',
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#2e5bff',
          },
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              // console.log(params)
              return '当日收益' + params.data + '元';
            }
          },
          itemStyle:{
            // borderWidth: 12,
            // borderType:'solid',
            // borderColor: 'rgba(255,255,255,0.5)'
            color: '#2e5bff',
          }
        },
        // areaStyle: {
        //   color: {
        //     type: 'linear',
        //     x: 0,
        //     y: 0,
        //     x2: 0,
        //     y2: 1,
        //     colorStops: [{
        //         offset: 0, color: 'rgba(255,255,255,0)' // 0% 处的颜色
        //     }, {
        //         offset: 1, color: 'rgba(255,255,255,0.2)' // 100% 处的颜色
        //     }],
        //     globalCoord: false // 缺省为 false
        //   }
        // },
        data: that.data.dataList
      }]
    };
    LineChart.hideLoading()
    return option;
  },

  //选择导航栏
  switchNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;      
    if (that.data.currentTab == cur) {
      return false;
    } else {
      that.setData({
        currentTab: cur
      })
      that.setEchartsData(cur);
    }
  },

  //给图表赋值
  setEchartsData:function(cur){
    var that = this
    var num =''
    switch (cur) {
      case 0:
        num = 7
        break;
      case 1:
        num = 30
        break;
    }
    that.setData({
      num2: num
    })
    that.getData()
  },

  //下级代理区域
  
  //picker
  bindCommunityChange: function (e) {
    var that = this
    console.log(e)
    if(that.data.communityArray){
      that.setData({
        isCommunity: true,
        communityIndex: e.detail.value,
        community: that.data.communityArray[e.detail.value],
        communityId: that.data.communityArray[e.detail.value].id,
        communityImgSrc: that.data.downImg
      })
      that.getData2()
    }
  },

  bindCommunityCancel:function(){
    this.setData({
      communityImgSrc: this.data.downImg
    })
  },

   //选择箭头
   imgChange:function(e){
    var that = this
    if(that.data.communityImgSrc == that.data.downImg){
      that.setData({
        communityImgSrc: that.data.upImg
      })
    }
  },

  //选择导航栏
  switchNav2(event){
    var that = this
    var cur = event.currentTarget.dataset.current;      
    if (that.data.currentTab2 == cur) {
      return false;
    } else {
      that.setData({
        currentTab2: cur
      })
      that.setEchartsData2(cur);
    }
  },

  //给图表赋值
  setEchartsData2:function(cur){
    var that = this
    var num =''
    switch (cur) {
      case 0:
        num = 7
        break;
      case 1:
        num = 30
        break;
    }
    that.setData({
      num3: num
    })
    that.getData2()
  },

  //获得数据
  getData2:function(){
    var that = this
    var start_time = (that.data.curTime - (that.data.num3 * 3600 * 24 * 1000)) / 1000;
    var end_time = (new Date(util.setTime(new Date()).replace(/-/g,"/") + ' 23:59:59').getTime())/1000;
    util.getAjax(`${app.globalData.apiUrl}/admin_community_get_community_sy_picture`,function(res){
      console.log(res)
      if(res.data.length != 0){
        var list = that.setNewList(res.data)
        list = list.reverse()
        var dateList = []
        var dataList = []
        for(var i in list){
          dateList.push(list[i].date);
          dataList.push(list[i].total_price.toFixed(2))
        }
        that.setData({
          isData: true,        
          dataList2: dataList,
          dateList2: dateList,
        })
        that.linechartsComponnet2 = that.selectComponent('#mychartLine2');
        LineChart2 = null
        that.getLineGraphData2();  //创建图表
      }else{
        that.setData({
          isData2: false
        })
      }
    },{community_id: that.data.communityId,start_time: start_time,end_time: end_time})
  },

  //线图表
  getLineGraphData2:function(){
    var that = this
    if (!LineChart2){
      that.init_LineEcharts2(); //初始化图表
    }else{
      that.setLineOption2(); //更新数据
    }
  },

  //初始化图表
  init_LineEcharts2: function () {
    var that = this
    that.linechartsComponnet2.init((canvas, width, height) => {
      // 初始化图表
      LineChart2 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      LineChart2.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setLineOption2();
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return LineChart;
    });
  },

  setLineOption2: function () {
    LineChart2.clear();  // 清除
    LineChart2.setOption(this.getLineOption2());  //获取新数据
  },

  //设置折线图表
  getLineOption2: function () {
    var that = this
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: '',
        subtext: ''
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:30,
        x2:0,
        y2:0,
        containLabel: true
      },
      xAxis: { 
        type: 'category',
        show:true,
        boundaryGap:true,
        data : that.data.dateList2,
        axisLine:{
          show:true,
          lineStyle:{
            color: '#e0e7ff',
            width: 1,
          }
        },
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          color: '#666666',
          interval: 0,
          formatter: '{value}',
          formatter:function(value){
            // console.log(value)
            return util.setTime3(value)
          }
        },
      },
      yAxis: {
        type: 'value',
        boundaryGap:false,
        show:true,
        scale: false,
        splitNumber:2,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine:{
          show:true,
          lineStyle:{
            color: '#e0e7ff',
          }
        },
        axisLabel:{
          show: true,
          inside: true,
          verticalAlign: 'bottom',
          margin: 0,
          color: '#666666',
          formatter:function(value,index){
            // console.log(value)
            return value + '元'
          }
        },
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: healthUtil.dataZoom(that.data.dateList2),
          end: 100,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'',
        type:'line',
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#2e5bff',
          },
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              // console.log(params)
              return '当日收益' + params.data + '元';
            }
          },
          itemStyle:{
            // borderWidth: 12,
            // borderType:'solid',
            // borderColor: 'rgba(255,255,255,0.5)'
            color: '#2e5bff',
          }
        },
        // areaStyle: {
        //   color: {
        //     type: 'linear',
        //     x: 0,
        //     y: 0,
        //     x2: 0,
        //     y2: 1,
        //     colorStops: [{
        //         offset: 0, color: 'rgba(255,255,255,0)' // 0% 处的颜色
        //     }, {
        //         offset: 1, color: 'rgba(255,255,255,0.2)' // 100% 处的颜色
        //     }],
        //     globalCoord: false // 缺省为 false
        //   }
        // },
        data: that.data.dataList2
      }]
    };
    LineChart2.hideLoading()
    return option;
  },



  //获取商品数据
  getShopAllData:function(classId){
    var urlType = ''
    switch (app.globalData.shopType) {
      case '0':
        urlType = 'get_service_product_xl';
        break;
      case '1':
        urlType = 'get_health_product_xl';
        break;
    }
    //获取商品数据
    util.getAjax(`${app.globalData.apiUrl}/${urlType}`,this.getShopData,{shop_id: app.globalData.shopId})
  },

  getShopData(res){
    var that = this
    console.log(res)
    if(res.data.length != 0){
      that.setData({
        isGoods: true,
      })
      that.processingEchartData(res.data)
    }else{
      that.setData({
        isGoods: false,
      })
    }
  },

  //获取图表数据
  processingEchartData:function(list){
    var that = this
    if(list && list.length != 0){
      var nameList = []
      var dataList = []
      for(var i in list){
        nameList.push(list[i].product_name)
        let data = ''
        switch (app.globalData.shopType) {
          case '0':
            data = list[i].all_pay?list[i].all_pay : 0
            break;
        
          case '1':
            data = list[i].pay_yes?list[i].pay_yes : 0
            break;
        }
       
        dataList.push(data)
      }
      that.setData({
        dataList2: dataList,
        nameList: nameList,
      })
      that.barchartsComponnet = that.selectComponent('#mychartBar');
      BarChart = null
      that.getBarGraphData();  //创建图表
    }
  },

  //线图表
  getBarGraphData:function(){
    var that = this
    if (!BarChart){
      that.init_BarEcharts(); //初始化图表
    }else{
      that.setBarOption(); //更新数据
    }
  },

  //初始化图表
  init_BarEcharts: function () {
    var that = this
    that.barchartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      BarChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      BarChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setBarOption();
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return BarChart;
    });
  },

  setBarOption: function () {
    BarChart.clear();  // 清除
    BarChart.setOption(this.getBarOption());  //获取新数据
  },

  //设置折线图表
  getBarOption: function () {
    var that = this
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: '',
        subtext: ''
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:30,
        x2:0,
        y2:0,
        containLabel: true
      },
      xAxis: { 
        type: 'category',
        show:true,
        boundaryGap:true,
        data : that.data.nameList,
        axisLine:{
          show:true,
          lineStyle:{
            color: '#e0e7ff',
            width: 1,
          }
        },
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          color: '#666666',
          interval: 0,
          formatter: '{value}',
          formatter:function(value){
            // console.log(value)
            var value = value.replace(/(.{4})/g, '$1\n')
            return value
          }
        },
      },
      yAxis: {
        type: 'value',
        boundaryGap:false,
        show:true,
        scale: false,
        splitNumber:2,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine:{
          show:true,
          lineStyle:{
            color: '#e0e7ff',
          }
        },
        axisLabel:{
          show: true,
          inside: true,
          verticalAlign: 'bottom',
          margin: 0,
          color: '#666666',
          formatter:function(value,index){
            // console.log(value)
            return value + '件'
          }
        },
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: healthUtil.dataZoom(that.data.nameList),
          end: 100,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'',
        type:'bar',
        itemStyle : {
          normal: {
            color: '#2e5bff',
          },
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              // console.log(params)
              return '已售' + params.data + '件';
            }
          },
          itemStyle:{
            // borderWidth: 12,
            // borderType:'solid',
            // borderColor: 'rgba(255,255,255,0.5)'
            color: '#2e5bff',
          }
        },
        barMaxWidth: 20,
        data: that.data.dataList2
      }]
    };
    BarChart.hideLoading()
    return option;
  },


   //回到顶部
   goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // console.log(e)
    if (e.scrollTop > 600) {
      this.setData({
        isTop: true
      });
    } else {
      this.setData({
        isTop: false
      });
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})